<template>
  <div>
    <div ref="main" style="height:calc(100vh - 85px);width: 100%;overflow-y: hidden;">
      <div style="position: absolute;top: 100px;z-index: 1000;left: 13px">
        <el-form
          :inline="true"
        >
          <el-form-item>
            <product-series-cascade @change="productChange"/>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="status"
              style="width: 100px;"
              :placeholder="$t('status')"
              @change="statusChange"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <province-city-cascade
              v-if="isInit"
              :status="status"
              :product-id="productId"
              :province-id="provinceId"
              :city-id="cityId"
              :series-id="seriesId"
              @change="provinceCityChange"
              @province-init="provinceInit"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="showList?'el-icon-caret-left':'el-icon-caret-right'"
              @click="showList=!showList"
            />
          </el-form-item>
          <el-form-item v-if="!zooMax">
            <el-button type="warning" icon="el-icon-full-screen" @click="requestFullScreen"/>
          </el-form-item>
          <el-form-item v-else>
            <el-button type="warning" icon="el-icon-crop" @click="exitFullscreen"/>
          </el-form-item>
        </el-form>
        <div v-show="showList" style="background: white;padding: 10px;border-radius: 10px">
          <div class="uni-scroll" style="height:calc(100vh - 210px);">
            <el-table
              ref="deviceTable"
              :show-header="false"
              :data="deviceList"
              style="width: 100%;"
              highlight-current-row
              @cell-click="deviceClick"
            >
              <el-table-column width="50">
                <template slot-scope="scope">
                  <el-image
                    slot="reference"
                    style="width: 40px; height:40px;margin: 8px 0 0 0"
                    :src="scope.row.iconUrl"
                    fit="fit"
                  />
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <div style="">
                    <div :class="scope.row.status" style="font-size:13px;line-height: 18px;">
                      <span>{{ scope.row.deviceName }}</span>
                      <span style="font-size:12px;color: #b3d3c2;">({{ scope.row.deviceCore }})</span>
                    </div>
                    <div style="font-size:12px;color: #b3d3c2; line-height: 14px;margin-top: 8px">{{
                        scope.row.address
                      }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column width="180">
                <template slot-scope="scope">
                  <div style="display: flex;justify-content: flex-end;margin-right: 5px">
                    <app-signal :signal="scope.row.signal" :status="scope.row.status"
                                :connect-type="scope.row.connectType" style="margin-right: 5px"
                    />
                    <app-surplus :device="scope.row"/>
                  </div>
                  <div style="display: flex;justify-content: flex-end">
                    <el-button-group style="margin-top: 3px">
                      <el-button round icon="el-icon-menu" @click.stop="deviceMore(scope.row)"/>
                      <el-button icon="el-icon-setting" @click.stop="deviceSetting(scope.row)"/>
                      <el-button icon="el-icon-s-platform" @click.stop="deviceSensor(scope.row)"/>
                    </el-button-group>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="text-align: center;width: 100%;margin-top: 5px">
            <el-pagination
              background
              :current-page.sync="currentPage"
              :page-size="pageSize"
              layout="total,sizes,prev,pager,next,jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      <div
        ref="map"
        style="height:calc(100vh);width: 100%"
      />
    </div>

    <el-dialog
      :visible.sync="showSetting"
      :title="device.deviceName"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="device.deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-drawer
      size="70%"
      :visible.sync="drawer"
      direction="rtl"
    >
      <div class="uni-scroll" style="height: calc(100vh - 100px)">
        <sensor-camera-list :device="device"/>
      </div>
    </el-drawer>

  </div>
</template>
<script>
import { exitFullscreen, formatDate, formatSensorType, listDeviceStatus, requestFullScreen } from '@/util/common'
import { pageGetDevice } from '@/api/iot/iotDeviceBelongApi'
import {
  getPageSize,
  getSearchDeviceStatus,
  getShowHidden,
  getUserId,
  setPageSize,
  setSearchDeviceStatus
} from '@/util/storage'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import ProductSeriesCascade from '@/components/ProductSeriesCascade'
import DeviceSetting from '@/components/DeviceSetting/index'
import SensorCameraList from '@/components/SensorCameraList'
import AppSurplus from '@/components/AppSurplus'
import AppSignal from '@/components/AppSignal'
import ProvinceCityCascade from '@/components/ProvinceCityCascade'
import {
  addMarketClickListener,
  clearAllMarket,
  hideInfoWindow,
  makeInfoWindow,
  makeMap,
  makeMarket,
  setCenter
} from '@/util/mapTool'

let map = null
let infoWindow = null
export default {
  name: 'AreaMap',
  components: {
    SensorCameraList,
    DeviceSetting,
    AppSurplus,
    AppSignal,
    ProductSeriesCascade,
    ProvinceCityCascade
  },
  data() {
    return {
      showList: false,
      drawer: false,
      showSetting: false,
      status: getSearchDeviceStatus(),
      infoWindow: null,
      statusList: [],
      map: null,
      markersArray: [],
      device: {},
      productId: null,
      seriesId: null,
      cityId: null,
      provinceId: null,
      userId: getUserId(),
      deviceList: [],
      // bounds: null,
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      isInit: false,
      zooMax: false,
      baseURL: window.VUE_APP_BASE_API,
      showHidden: getShowHidden()

    }
  },
  mounted() {
    this.isInit = true
    this.statusList = listDeviceStatus(this)
    map = makeMap(this.$refs.map, null, null)
    window.mapDeviceSensor = this.mapDeviceSensor
    window.mapDeviceMore = this.mapDeviceMore
    window.mapDeviceSetting = this.mapDeviceSetting
  },
  methods: {
    requestFullScreen() {
      requestFullScreen(this.$refs.main)
      this.zooMax = true
    },
    exitFullscreen() {
      exitFullscreen()
      this.zooMax = false
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetDevice()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetDevice()
    },
    /**
     * 按省级获取设备数量
     */
    provinceInit(data) {
      this.currentPage = 1
      this.device = {}
      this.deviceList = []
      this.changeMarker(data.productList)
    },
    changeMarker(productList) {
      clearAllMarket(map)
      hideInfoWindow(map, infoWindow)
      for (const i in productList) {
        const product = productList[i]
        let iconUrl
        if (product.num >= 99) {
          iconUrl = `${this.baseURL}/file/download/static/iot/uni/map/numsImage/blue/local_99.png`
        } else {
          iconUrl = `${this.baseURL}/file/download/static/iot/uni/map/numsImage/blue/local_${product.num}.png`
        }
        const marker = makeMarket(map, product.lat, product.lng, iconUrl)
        marker.ztn.provinceId = product.provinceId
        marker.ztn.cityId = product.cityId

        const that = this
        addMarketClickListener(map, marker, () => {
          that.provinceId = marker.ztn.provinceId
          that.cityId = marker.ztn.cityId
          that.pageGetDevice()
        })
      }
    },
    deviceMore(item) {
      this.$router.push({
        path: '/device/manage/' + item.deviceCore,
        query: {
          deviceCore: item.deviceCore,
          deviceName: item.deviceName
        }
      })
    },
    deviceSetting(item) {
      this.deviceClick(item)
      this.showSetting = true
    },
    getSensor(item) {
      this.deviceClick(item)
      this.drawer = true
    },
    listSensorWith(device) {
      listSensorWith({
        deviceCore: device.deviceCore,
        withExplain: true,
        withParam: true,
        withSetting: false
      }).then(res => {
        const { code, data } = res
        const sensorList = []
        if (code === '200') {
          for (const item of data) {
            if (item.hidden) {
              continue
            }
            if (!item.explainList) {
              item.explainList = []
            }
            if (!item.settingList) {
              item.settingList = []
            }
            if (!item.paramList) {
              item.paramList = []
            }
            if (item.explainList.length > 0 || item.settingList.length > 0 || item.paramList.length > 0) {
              sensorList.push(item)
            }
          }
        }
        this.showMapInfo(device, sensorList)
      })
    },
    showMapInfo(device, sensorList) {
      let content = `<div style="width: 200px">
                      <div>${device.deviceName}</div>`

      sensorList.forEach(sensor => {
        if (this.showHidden !== '1' && sensor.hidden) {
          return
        }
        content = content + `<div style="margin: 13px 0;font-size: 13px;color: #e7cc69;">
                                <span style="margin-right: 5px">${sensor.sensorName}</span>
                                <span>[${this.formatSensorType(sensor.type)}${this.$t('port')}:${sensor.port}]</span>
                              </div>`
        sensor.explainList.forEach(explain => {
          if (this.showHidden !== '1' && explain.hidden) {
            return
          }
          content = content + `<div style="height: 20px;width: 100%">
                                    <span style="color: #99a9bf;width: 100px;font-size: 13px">${explain.name}<span style="color: #606266;font-size: 13px;float: right">${explain.value}${explain.unit}</span></span>
                               </div>`
        })
      })
      content = content + `<div style="width: 100%;height: 20px;">
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-menu " style="font-size: 15px" onclick="mapDeviceMore('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-setting" style="font-size: 15px" onclick="mapDeviceSetting('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-s-platform" style="font-size: 15px" onclick="mapDeviceSensor('${device.deviceCore}')" />
                        </div>
                      </div>
                    </div>`
      infoWindow = makeInfoWindow(map, device.lat, device.lng, content)
    },
    deviceClick(item) {
      console.log(map.ztn.markerList)
      this.device = item
      hideInfoWindow(map, infoWindow)
      for (let i = 0, j = map.ztn.markerList.length; i < j; i++) {
        if (map.ztn.markerList[i].ztn.device.deviceCore === item.deviceCore) {
          const marker = map.ztn.markerList[i]
          if (this.showList) {
            setCenter(map, marker.lat, marker.lng)
          }
          this.listSensorWith(item)
          return
        }
      }
    },
    deviceSensor(item) {
      this.deviceClick(item)
      this.drawer = true
    },
    statusChange(val) {
      setSearchDeviceStatus(this.status)
    },
    productChange(val) {
      this.productId = val.productId
      this.seriesId = val.seriesId
    },
    makeMarker(device) {
      const marker = makeMarket(map, device.lat, device.lng, device.iconUrl)
      marker.ztn.device = device
      const that = this
      addMarketClickListener(map, marker, (param) => {
        that.$refs.deviceTable.setCurrentRow(param.marker.ztn.device)
        that.deviceClick(param.marker.ztn.device)
      })
      return marker
    },
    mapDeviceMore(deviceCore) {
      this.deviceList.forEach(device => {
        if (device.deviceCore === deviceCore) {
          this.deviceMore(device)
          return
        }
      })
    },
    mapDeviceSetting(deviceCore) {
      this.deviceList.forEach(device => {
        if (device.deviceCore === deviceCore) {
          this.deviceSetting(device)
          return
        }
      })
    },
    mapDeviceSensor(deviceCore) {
      this.deviceList.forEach(device => {
        if (device.deviceCore === deviceCore) {
          this.deviceSensor(device)
          return
        }
      })
    },
    provinceCityChange(item) {
      this.provinceId = item.provinceId
      this.cityId = item.cityId
      this.currentPage = 1
      this.pageGetDevice()
    },
    pageGetDevice() {
      clearAllMarket(map)
      const req = {
        productId: this.productId,
        status: this.status,
        provinceId: this.provinceId,
        cityId: this.cityId,
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        userId: this.userId
      }

      pageGetDevice(req).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.total = data.total
          this.deviceList = data.data
          for (let i = 0, j = data.data.length; i < j; i++) {
            this.makeMarker(data.data[i], i)
          }
        }
      })
    }
  }
}
</script>

